# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(optparse)
library(tidyverse)
library(showtext)
showtext_auto()

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "data.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

sampleInfo <- read_csv(opt$g) %>%
  rename(ClassNote = Group) %>%
  select(c("SampleID", "ClassNote"))

head(sampleInfo)

originalData <- read_csv(opt$i) %>%
  rename(Metabolite = SampleID)

data <- originalData %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  inner_join(sampleInfo, by = c("SampleID"))

numColumns <- colnames(data) %>%
  keep(function(x) {
    startsWith(x, "Nubmer") || startsWith(x, "Number")
  })

data <- data %>%
  mutate_at(vars(numColumns), as.numeric) %>%
  mutate_at(vars(-numColumns), factor)

getRoc <- function(name) {
  x <- data[name] %>%
    unlist() %>%
    as.ordered()
  y <- data$ClassNote
  rocRs <- roc(y, x, ci = T)
  return(list(name = name, roc = rocRs))
}

rocs <- originalData %>%
  .$Metabolite %>%
  unique() %>%
  map(getRoc)

aucData <- rocs %>%
  map_dfr(function(rocList) {
    rocRs <- rocList$roc
    name <- rocList$name
    auc <- round(rocRs$auc, 3)
    return(data.frame(name = name, auc = auc))
  }) %>%
  arrange(desc(auc))

aucNames <- aucData$name

breaks <- seq(0, 1, by = 0.2)

colors <- hsv(h = seq(0, 1, length = 100) * 0.8, s = 1, v = 1)
yBreaks <- seq(0, 1, 0.2)

getP <- function(name) {
  list <- rocs %>%
    detect(function(rocList) {
      rocList$name == name
    })
  rocRs <- list$roc
  ci <- rocRs$ci
  ci1 <- ci[1] %>%
    round(3)
  ci2 <- ci[3] %>%
    round(3)
  auc <- round(rocRs$auc, 3)

  pointData <- coords(rocRs, "best", transpose = T) %>%
    round(3) %>%
    as.data.frame() %>%
    rownames_to_column("Name") %>%
    select(1:2) %>%
    gather("Kind", "Value", -Name) %>%
    spread(Name, "Value")

  plotData <- tibble(sensitivity = rocRs$sensitivities, specificity = rocRs$specificities, threshold = rocRs$thresholds) %>%
    mutate(specificity = 1 - specificity) %>%
    arrange(sensitivity)

  p <- ggplot(data = plotData, aes(x = specificity, y = sensitivity, color = threshold)) +
    theme_bw(base_size = 8.8, base_family = "Times") +
    theme(plot.title = element_text(size = 14, hjust = 0.5, face = "bold"), panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(), axis.title.x = element_text(size = 14), axis.title.y = element_text(size = 14),
          axis.text.x = element_text(size = 12), axis.text.y = element_text(size = 12),
          plot.margin = unit(c(1, 0.5, 1, 0.5), "cm"), panel.border = element_rect(size = 0.75),
          legend.text = element_text(size = 9), legend.title = element_text(size = 11)
    ) +
    ggtitle(str_replace(name, "/", "/\n")) +
    labs(colour = "Cutoff") +
    geom_line() +
    geom_abline(intercept = 0, slope = 1, color = "grey", linetype = 1, size = 0.4) +
    annotate("text", x = 0.5 + 0.01, y = 0.5, label = str_c("AUC:", auc, "(", ci1, ",", ci2, ")"), color = "black",
             hjust = 0, size = 4.3, family = "Times") +
    geom_point(data = pointData, aes(x = 1 - specificity, y = sensitivity), size = 1, color = "red") +
    geom_text(data = pointData, aes(x = 1 - specificity, y = sensitivity, label = paste0(threshold,
                                                                                         "(", specificity, ",", sensitivity, ")")), color = "black", hjust = 0, vjust = 1, size = 3, nudge_x = 0.015,
              nudge_y = -0.015, family = "Times") +
    scale_x_continuous("1 - Specificity", breaks = yBreaks) +
    scale_y_continuous("Sensitivity", breaks = seq(0, 1, 0.2)) +
    scale_colour_gradientn(colours = colors)

  return(p)
}

p <- aucNames %>%
  map(getP)

pdfFileName <- "Single_Var_ROC.pdf"
pdf(pdfFileName, 6, 6)
for (i in seq(1, length(p), 1)) {
  plot.new()
  iEnd <- i
  inP <- p[i:iEnd] %>%
    map(function(x) {
      if (is.null(x)) {
        p <- ggplot() + theme_void()
        p
      }else x
    })
  inEnd <- min(3, length(inP))
  inP[1:inEnd] = inP[1:inEnd] #%>%
  # map(~ .x + theme(plot.margin = margin(t = 0.5, l = 0.5, r = 0.5, b = 0.5, unit = "cm")))
  ggarrange(plots = inP, ncol = 1, newpage = F)
}
dev.off()









